package com.itsfoodme.login;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import oauth.signpost.OAuth;

import org.json.JSONException;
import org.json.JSONObject;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.http.AccessToken;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.facebook.android.*;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.Facebook.*;

public class AouthLoginActivity extends Activity {
	//para FB 
	Facebook facebook = new Facebook("220432691406800");
	private SharedPreferences mPrefs;
	private AsyncFacebookRunner mAsyncRunner;
	//para twitter
	private SharedPreferences prefs;
	
	Button btnFbLogin;
	Button btnTwitterLogin;
	Button btnTwitterLogOut;
	TextView txtStatus;
	ImageView imgProfile;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        
        btnFbLogin = (Button) findViewById(R.id.btn_fblogin);
        btnTwitterLogin = (Button) findViewById(R.id.btn_Twtlogin);
        btnTwitterLogOut = (Button) findViewById(R.id.btn_TwtlogOut);
        
        //para FB
        mAsyncRunner = new AsyncFacebookRunner(facebook);
        
        //para Twt
        this.prefs = PreferenceManager.getDefaultSharedPreferences(this);
        
		btnFbLogin.setOnClickListener(new View.OnClickListener() {

			//@Override
			public void onClick(View v) {
				Log.d("Ogin Button", "FB login BTN");
				loginToFacebook();
			}
		});

		btnTwitterLogin.setOnClickListener(new View.OnClickListener() {
			//@Override
			public void onClick(View v) {
				if (TwitterUtils.isAuthenticated(prefs)) {
					
					String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
					String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");
					AccessToken a = new AccessToken(token,secret);
					Twitter twitter = new TwitterFactory().getInstance();
					twitter.setOAuthConsumer(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
					twitter.setOAuthAccessToken(a);
					
					String twtsn;
					String twtn_id="#";
					try {
						twtsn = twitter.getScreenName().toString();
						twtn_id = String.valueOf(twitter.showUser(twtsn).getId());
					} catch (IllegalStateException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (TwitterException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					istFoodApi Call = new istFoodApi();
					if(twtn_id=="#"){
						Toast.makeText(getApplicationContext(), "Ocurrio un error al Logearse, Intenta de nuevo", Toast.LENGTH_SHORT).show();
					}else if( Call.postDataL(twtn_id, "Tw", "login")){
						Intent myIntent = new Intent(v.getContext(), MainPage.class);
		                startActivityForResult(myIntent, 0);
					}else{
						String[] user = TwitterSatusDetails(twitter);
						Intent intent = new Intent(v.getContext(), FormPage.class);
						intent.putExtra("User_Info", user);
						startActivityForResult(intent, 0);
					}
		    	} else {
		    		 Intent i = new Intent(getApplicationContext(), PrepareRequestTokenActivity.class);
					 startActivity(i);
		    	}
		    }
		});
		
		btnTwitterLogOut.setOnClickListener(new View.OnClickListener() {
			//@Override
			public void onClick(View v) {
				Log.d("LogOut Button", "button Clicked");
				clearCredentialsTwitter();
			}
		});
		
    }

    /**
	 * Fb Graph API
	 * */
	public void loginToFacebook() {
        mPrefs = getPreferences(MODE_PRIVATE);
        String access_token = mPrefs.getString("access_token", null);
        long expires = mPrefs.getLong("access_expires", 0);
        if(access_token != null) {
            facebook.setAccessToken(access_token);
            btnFbLogin.setVisibility(View.INVISIBLE);
            Log.d("FB Sessions", "" + facebook.isSessionValid());  
        }
        if(expires != 0) {
            facebook.setAccessExpires(expires);
        }
        
        /*
         * Only call authorize if the access_token has expired.
         */
        if(!facebook.isSessionValid()) {

            facebook.authorize(this, new String[] {}, new DialogListener() {
                //@Override
                public void onComplete(Bundle values) {
                	btnFbLogin.setVisibility(View.INVISIBLE);
                    SharedPreferences.Editor editor = mPrefs.edit();
                    editor.putString("access_token", facebook.getAccessToken());
                    editor.putLong("access_expires", facebook.getAccessExpires());
                    editor.commit();
                    
                    mAsyncRunner.request("me", new RequestListener() {
            			//@Override
            			public void onComplete(String response, Object state) {
            				Log.d("Profile", response);
            				String json = response;
            				String [] U = {" "," "," "," "," "," "," "," "," "," "," "," "," "};
            				try{
								JSONObject profile = new JSONObject(json);
								U[0] = "Fb";
            					U[1] = profile.getString("id");
            					U[2] = profile.getString("username");
            					U[3] = profile.getString("first_name");
            					U[4] = profile.getString("last_name");
            					U[5] = "http://graph.facebook.com/"+U[2]+"/picture";
            					U[8] = Character.toUpperCase(profile.getString("gender").charAt(0)) + profile.getString("gender").substring(1);
            					U[9] = " ";
            					try{
            					U[10] = profile.getString("email");
            					}catch(JSONException a){
            						a.printStackTrace();
            					}
            					try{
            						U[11] = profile.getString("birthday");
	            				}catch(JSONException a){
	        						a.printStackTrace();
	        					}
            					U[12] = facebook.getAccessToken();
            					
            					istFoodApi Call = new istFoodApi();
            					
            					if(Call.postDataL(U[1], "Fb", "login")){
            						startActivity(new Intent(AouthLoginActivity.this, MainPage.class));
            					}else{
            						Intent intent = new Intent(AouthLoginActivity.this, FormPage.class);
            						intent.putExtra("User_Info", U);
            						startActivity(intent);
            					}
            					
            				} catch (JSONException ex) {
            					ex.printStackTrace();
            				}
            				
						}
    
						
						//@Override
						public void onIOException(IOException e, Object state) {
							// TODO Auto-generated method stub
							
						}
						//@Override
						public void onFacebookError(FacebookError e, Object state) {
							// TODO Auto-generated method stub
						}


						public void onFileNotFoundException(
								FileNotFoundException e, Object state) {
							// TODO Auto-generated method stub
							
						}


						public void onMalformedURLException(
								MalformedURLException e, Object state) {
							// TODO Auto-generated method stub
							
						}
					});
				}

				//@Override
				public void onFacebookError(FacebookError e) {
					// TODO Auto-generated method stub	
				}

				//@Override
				public void onError(DialogError e) {
					// TODO Auto-generated method stub
				}

				//@Override
				public void onCancel() {
					// TODO Auto-generated method stub
				}
            });
        }
    }
   
    public void onResume() {    
        super.onResume();
        facebook.extendAccessTokenIfNeeded(this, null);
    }
    
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        facebook.authorizeCallback(requestCode, resultCode, data);
    }
	
	public void logoutFromFacebook() {
		mAsyncRunner.logout(this.getBaseContext(), new RequestListener() {
			//@Override
			public void onComplete(String response, Object state) {
				Log.d("Logout from Facebook", response);
				if (Boolean.parseBoolean(response) == true) {
					runOnUiThread(new Runnable() {
						
						//@Override
						public void run() {
							// make Login button visible
							btnFbLogin.setVisibility(View.VISIBLE);
							txtStatus.setText("Y u no Login?");
						}

					});

				}
			}

			//@Override
			public void onIOException(IOException e, Object state) {
			}

			//@Override
			public void onFileNotFoundException(FileNotFoundException e,
					Object state) {
			}

			//@Override
			public void onMalformedURLException(MalformedURLException e,
					Object state) {
			}

			//@Override
			public void onFacebookError(FacebookError e, Object state) {
			}
		});
	}
	
	/**
	 *Para Twitter 
	 **/
	private void clearCredentialsTwitter() {
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		final Editor edit = prefs.edit();
		edit.remove(OAuth.OAUTH_TOKEN);
		edit.remove(OAuth.OAUTH_TOKEN_SECRET);
		edit.commit();
		//txtStatus.setText("Y u no Login?");
	}
	
	private String[] TwitterSatusDetails(Twitter twitter){
		String [] U= new String [7];
		try {
			String twtsn = twitter.getScreenName().toString();
			String twtn_id = String.valueOf(twitter.showUser(twtsn).getId());
			String twtn_name = String.valueOf(twitter.showUser(twtsn).getName());
			U[0]="Tw";
			U[1]=twtn_id;
			U[2]=twtsn;
			U[3]=twtn_name;
			U[4]=" ";
			U[5]=String.valueOf(twitter.showUser(twtsn).getProfileImageURL());
			U[6]=twitter.showUser(twtsn).getLocation();
			U[7]= prefs.getString(OAuth.OAUTH_TOKEN, "")+","+prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (TwitterException e) {
			e.printStackTrace();
		}
		return U;
	}
}